<?php
            
use app\model\Comm; 
use app\model\Theme; 
use app\model\Worker; 
use app\model\Fans; 
use app\model\Userdata; 


/**
 * Desc:
 * Time: 2021/5/27 1:35 下午
 */
require_once PATH_MODULE .'define.php';
class GiftModel extends PluginModel
{
    /**
     * Desc: 礼品记录处理
     * User: mf
     * Time: 2023/10/24 13:38
     * @param $uid
     * @param $themeid
     * @param $gift_id  礼物ID;
     * @param $status  1 已经领取
     * @param $taskid 任务ID 当前获得哪个任务的礼品
     * @param $classify  区分任务类型   邀请礼：invite_gift 成团礼：tuan_gift
     * @param $freeze  0为冻结；1为解冻
     * @return array
     */
    public static function giftProcessing($uid,$themeid,$gift_id,$status=1,$taskid='',$classify='',$freeze=0,$pid)
    {
        $insert = [];
        $insert['themeid'] = $themeid;
        $insert['uid'] = $uid;
        $insert['gift_id'] = $gift_id;
        $insert['status'] = $status;
        $insert['classify'] = $classify;
        $insert['taskid'] = $taskid;
        $insert['pid'] = $pid;

        if(empty($uid)||$uid<1){
            yxlog($insert,'邀请礼写入错误-用户身份缺失');
            return ;
        }
        if(empty($themeid)){
            yxlog($insert,'邀请礼写入错误-活动ID缺失');
            return ;
        }
        if(empty($gift_id)){
            yxlog($insert,'邀请礼写入错误-礼品参数缺失');
            return ;
        }
        if(empty($status)){
            yxlog($insert,'邀请礼写入错误-状态缺失');
            return ;
        }
        if(empty($taskid)){
            yxlog($insert,'邀请礼写入错误-参数缺失');
            return ;
        }
        if(empty($classify)){
            yxlog($insert,'邀请礼写入错误-参数缺失');
            return ;
        }

        //查找礼品
        $gift = db_get(t_intive_gift,array('id'=>$gift_id));
        if(empty($gift)){
            yxlog($insert,'邀请礼写入错误-未找到礼品');
            return ;
        }
        if($gift['status']==0){
            yxlog($insert,'邀请礼写入错误-礼品已下架');
            return ;
        }
        $worker = db_get(t_worker,array('uid'=>$uid));
        if($worker){
            yxlog($insert,'邀请礼写入错误-员工不可参与');
            return ;
        }

        if($classify=='tuan_gift'){
            //礼品订单信息
            $record = db_get(t_intive_gift_record,array('themeid'=>$themeid,'uid'=>$uid,'taskid'=>$taskid,'classify'=>$classify,'pid'=>$pid),array('id'));
        }
        if($classify=='invite_gift'||$classify=='help_gift'){
            //礼品订单信息
            $record = db_get(t_intive_gift_record,array('themeid'=>$themeid,'uid'=>$uid,'taskid'=>$taskid,'classify'=>$classify),array('id','freeze'));
            if(!empty($record)&&$freeze==1&&$record['freeze']==0){
                db_update(t_intive_gift_record,array('freeze'=>1),array('id'=>$record['id']));
                yxlog($insert,'邀请礼-解冻礼品');
                return ;
            }
        }
        if(!empty($record)){
//            yxlog($insert,'邀请礼写入错误-已获得过该任务礼品');
            return ;
        }

        $insert['freeze'] = $freeze;
        $insert['shangjiaid'] = $gift['shangjiaid'];
        $insert['type'] = $gift['type'];
        $result = $insertid = db_insert(t_intive_gift_record,$insert);
        if (!empty($result)) {
            if($gift['type']==2){//判断是红包（用户领取时直接发放，跳过状态1，变成2）
                $gift_record_id = $insertid;
                $fans = self::getUserInfoById($uid,$themeid);
                $comm_id = self::redEnvelope($gift['price'],$themeid,$fans,$gift_record_id,$fans['fromuid']);
                if ($comm_id){
                    //用户日志收集
                    Userdata::addLog($themeid, $fans['uid'], 14, '邀请礼红包发放');
                    db_update(t_intive_gift_record,array('status'=>2),array('id'=>$gift_record_id));
                }
            }
            return ['errcode'=>'200','errmsg'=>'ok'];
        }else{
            yxlog($insert,'邀请礼写入错误-sql写入失败');
            return ['errcode'=>'201','errmsg'=>'no'];
        }
    }

    /**
     * Desc:领取礼品验证
     * User: mf
     * Time: 2023/10/25 15:57
     * @param $themeid
     * @param $recordid
     */
    public static function authentication($themeid,$recordid)
    {
       /**
        * 成团礼：拼团人数达到要求，给符合'身份'、'条件'人的奖励。1、2
        * 邀请礼：A邀请别人下单，达到条件给A奖励。 条件是限制A的条件 。0、1、3、4
        */
        $gift_config = db_get(t_intive_gift_config,array('software'=>MODULE_NAME,'themeid'=>$themeid));
        $time = date("Y-m-d H:i:s",time());
        $theme = Theme::getThemeById($themeid);
        if($gift_config['is_limit_time']==1){
            if($time<$gift_config['limit_start_time']||$time>$gift_config['limit_end_time']){
                yxlog($gift_config,'邀请礼写入错误-不在时间范围内');
                return false;
            }
        }else{
            if(time()<$theme['begintime']||time()>$theme['endtime']){
                yxlog(['begintime'=>$theme['begintime'],'endtime'=>$theme['endtime']],'邀请礼写入错误-不在时间范围内');
                return false;
            }
        }
        $status = " AND (status=1 OR status=3 OR status=-2)  ";
        //订单信息
        $record = db_find("SELECT pid,uid,fromuid FROM ".tablename(t_record)." WHERE  themeid='$themeid'  AND id='$recordid'".$status);
        if(empty($record)){
            yxlog(['$recordid'=>$recordid,'$themeid'=>$themeid],'邀请礼领取错误-未找到订单');
            return false;
        }
        $help_gift=$tuan_gift=$invite_gift = [];
        if($gift_config['open_tuan_gift']==1&&!empty($gift_config['tuan_gift'])){
            $tuan_gift = GiftModel::format($gift_config['tuan_gift'],'tuan_gift');
        }
        if($gift_config['open_invite_gift']==1&&!empty($gift_config['invite_gift'])){
            $invite_gift = GiftModel::format($gift_config['invite_gift'], 'invite_gift');
        }
        if($gift_config['open_help_gift']==1&&!empty($gift_config['help_gift'])){
            $help_gift = GiftModel::format($gift_config['help_gift'], 'help_gift');
        }
        //成团礼
        if($gift_config['open_tuan_gift']==1&&!empty($tuan_gift)){
            //团总数
            $recordall = db_select("SELECT id,uid,pid,type FROM ".tablename(t_record)." WHERE  themeid='$themeid'  AND pid=".$record['pid'].$status);;
            $record_number = count($recordall);
            foreach ($tuan_gift as $key => $value){
                if($value['status']==2){
                    continue;
                }
                //判断人数是否符合条件
                if($record_number>=$value['number']){
                    //判断团长可获得礼品
                    if($value['identity']==1){
                        //查询团长uid
                        $p_record = db_find("SELECT uid FROM ".tablename(t_record)." WHERE  themeid='$themeid'  AND id='".$record['pid']."'".$status);
                        if(!empty($p_record)){
                            self::giftProcessing($p_record['uid'],$themeid,$value['gift_id'],1,$value['taskid'],'tuan_gift',1,$record['pid']);
                        }
                    }
                    //判断团长团员都可获得礼品
                    if($value['identity']==2){
                        foreach ($recordall as $index => $item) {
                            self::giftProcessing($item['uid'],$themeid,$value['gift_id'],1,$value['taskid'],'tuan_gift',1,$record['pid']);
                        }
                    }
                    //判断团员可获得礼品
                    if($value['identity']==3){
                        foreach ($recordall as $index => $item) {
                            if($item['type']==1){
                                self::giftProcessing($item['uid'],$themeid,$value['gift_id'],1,$value['taskid'],'tuan_gift',1,$record['pid']);
                            }
                        }
                    }

                }
            }
        }
        //邀请礼
        if($gift_config['open_invite_gift']==1&&!empty($invite_gift)){
            //判断当前订单有fromuid且不等于0 推荐人uid不等于自己uid
            if(!empty($record['fromuid'])&&$record['fromuid']!=0&&$record['uid']!=$record['fromuid']){
                //查询邀请人，邀请了多少个订单。对订单uid进行去重，被邀请人所有订单只统计一次
                $record_number = GiftModel::recordCount($themeid,$record['fromuid']);
                foreach ($invite_gift as $key => $value){
                    if($value['status']==2){
                        continue;
                    }
                    $freeze = 0;
                    //判断人数是否符合条件
                    if($value['number']<=$record_number){
                         //判断邀请人 不限制身份
                        if($value['identity']==0){
                            $freeze=1;
                            self::giftProcessing($record['fromuid'],$themeid,$value['gift_id'],1,$value['taskid'],'invite_gift',$freeze,$record['pid']);
                        }
                        //判断邀请人 必须支付过订单
                        if($value['identity']==4){
                            //查询邀请人 支付订单
                            $p_record = db_find("SELECT uid FROM ".tablename(t_record)." WHERE  themeid='$themeid'  AND uid='".$record['fromuid']."'".$status);
                            if(!empty($p_record)){
                                $freeze = 1;
                            }
                            self::giftProcessing($p_record['uid'],$themeid,$value['gift_id'],1,$value['taskid'],'invite_gift',$freeze,$record['pid']);
                        }
                        //判断邀请人 必须是团长
                        if($value['identity']==1){
                            //查询邀请人 团长订单
                            $p_record = db_find("SELECT uid FROM ".tablename(t_record)." WHERE  themeid='$themeid'  AND uid='".$record['fromuid']."' AND type=0  ".$status);
                            if(!empty($p_record)){
                                $freeze = 1;
                            }
                            self::giftProcessing($p_record['uid'],$themeid,$value['gift_id'],1,$value['taskid'],'invite_gift',$freeze,$record['pid']);
                        }
                        //判断邀请人 必须是团员
                        if($value['identity']==3){
                            //查询邀请人 团员订单
                            $p_record = db_find("SELECT uid FROM ".tablename(t_record)." WHERE  themeid='$themeid'  AND uid='".$record['fromuid']."' AND type=1   ".$status);
                            if(!empty($p_record)){
                                $freeze = 1;
                            }
                            self::giftProcessing($p_record['uid'],$themeid,$value['gift_id'],1,$value['taskid'],'invite_gift',$freeze,$record['pid']);
                        }
                    }
                }
            }
        }
        //助力礼
        if($gift_config['open_help_gift']==1&&!empty($help_gift)){
            //当前人的推荐人
            $friend = db_get(t_friend,array('themeid'=>$themeid,'id'=>$recordid),array('id','fromuid'));
            //推荐人推荐的数量
            $friendall = db_getall(t_friend,array('themeid'=>$themeid,'fromuid'=>$friend['fromuid']),array('id'));
            $friend_number = count($friendall);
            foreach ($help_gift as $key => $value){
                if($value['status']==2){
                    continue;
                }
                //判断人数是否符合条件
                if($friend_number==$value['number']){
                    self::giftProcessing($friend['fromuid'],$themeid,$value['gift_id'],1,$value['taskid'],'help_gift',1,0);
                }
            }
        }
        return true;
    }

    /**
     * Desc: 退款处理
     * User: mf
     * Time: 2023/10/31 17:36
     * @param $themeid
     * @param $record
     */
    public static function refund($themeid,$record)
    {
        $status = " AND (status=1 OR status=3 OR status=-2)  ";
        //订单信息
//        $record = db_find("SELECT pid,uid,fromuid FROM ".tablename(t_record)." WHERE  themeid='$themeid'  AND id='$recordid' AND status=-1");
        $gift_config = db_get(t_intive_gift_config,array('software'=>MODULE_NAME,'themeid'=>$themeid));
        $tuan_gift = json_decode($gift_config['tuan_gift'],true);
        $invite_gift = json_decode($gift_config['invite_gift'],true);
        if(!empty($record)){
            //成团礼
            if(!empty($tuan_gift)){
                //删除本人本团的所有成团礼（未核销的）
                db_delete(t_intive_gift_record, array('themeid'=>$themeid,'pid' => $record['pid'],'uid'=>$record['uid'],'classify'=>'tuan_gift','status'=>1));
                $recordall = db_select("SELECT id,uid FROM ".tablename(t_record)." WHERE  themeid='$themeid'  AND pid='".$record['pid']."'   ".$status);
                $record_number = count($recordall);
                foreach ($tuan_gift as $key => $value){
                    //当前人数小于条件人数且有发放记录的，删除发放记录
                    if($record_number<$value['number']){
                        //查询礼品订单信息
                        $gift_record = db_get(t_intive_gift_record,array('themeid'=>$themeid,'pid'=>$record['pid'],'taskid'=>$value['taskid'],'classify'=>'tuan_gift'),array('id'));
                        if(!empty($gift_record)){
                            db_delete(t_intive_gift_record, array('themeid'=>$themeid,'pid' => $record['pid'],'classify'=>'tuan_gift','taskid'=>$value['taskid'],'status'=>1));
                        }
                    }
                }
            }
            //邀请礼
            if(!empty($invite_gift)){
                //删除本人的所有邀请礼（未核销的）
                db_delete(t_intive_gift_record, array('themeid'=>$themeid,'uid'=>$record['uid'],'classify'=>'invite_gift','status'=>1));
                //查询当前订单的上级邀请了多少人下单，被邀请人所有订单只统计一次
                $record_number = GiftModel::recordCount($themeid,$record['fromuid']);
                foreach ($invite_gift as $key => $value){
                    //当前人数小于条件且有发放记录的，删除发放记录
                    if($record_number<$value['number']){
                        //查询礼品订单信息
                        $gift_record = db_get(t_intive_gift_record,array('themeid'=>$themeid,'uid'=>$record['fromuid'],'taskid'=>$value['taskid'],'classify'=>'invite_gift'),array('id'));
                        if(!empty($gift_record)){
                            db_delete(t_intive_gift_record, array('id'=>$gift_record['id'],'status'=>1));
                        }
                    }
                }

            }
        }
        return;
    }

    /**
     * Desc: 统计邀请礼 邀请的人数，提出了虚拟订单 邀请人是自己的问题
     * User: mf
     * Time: 2023/11/25 11:07
     * @param $themeid
     * @param $uid
     * @return int
     */
    public static function recordCount($themeid,$uid)
    {
        $record = db_select("SELECT id FROM " . tablename(t_record) . "  WHERE themeid='$themeid' AND  fromuid=" . $uid . " AND (status=1 OR status=3 OR status=-2) AND uid!=".$uid." GROUP  BY  uid");
        return count($record);
    }

    /**
     * Desc:批量校验礼品
     * User: mf
     * Time: 2023/11/27 16:05
     * @param $themeid
     */
    public static function validation($themeid,$page)
    {

        $page = $page*50;
        $recordall = db_select("SELECT id FROM " . tablename(t_record) . "  WHERE themeid='$themeid'  AND (status=1 OR status=3 OR status=-2) LIMIT $page,50 ");
        $count = count($recordall);
        if($count==0){
            return 'fail';
        }
        foreach ($recordall as  $value){
            self::authentication($themeid,$value['id']);
        }
        return 'success';
    }
    /**
     * Desc:红包发放
     * User: mf
     * Time: 2023/11/7 14:35
     * @param $amount  金额
     * @param $themeid
     * @param $fans
     * @param $gift_record_id
     * @param $fromuid
     * @return mixed
     */
    public static function redEnvelope ($amount,$themeid,$fans,$gift_record_id,$fromuid)
    {
        $data = array(
            'uniacid'    => $fans['uniacid'],
            'themeid'    => $themeid,
            'recordid'   => $gift_record_id,
            'ordersn'    => time().rand(10000,99999),
            'type'       => 14,
            'openid'     => $fans['openid'],
            'uid'     => $fans['uid'],
            'addtime'    => TIMESTAMP,
            'fee'        => $amount,
            'fopenid'    => $fans['fopenid'],
            'fromuid'    => $fromuid,
            'openid_old'     => $fans['openid_old'],
            'uid_old'     => $fans['uid_old'],
            'fopenid_old'    => $fans['fopenid_old'],
            'fromuid_old'    => $fans['fromuid_old'],
            'status'     =>0,
        );
        return Comm::add_share_comm($data);
    }
    /**
     * Desc:格式化
     * User: mf
     * Time: 2023/10/28 09:42
     * @param $array
     * @param $type
     * @return array|mixed
     */
    public static function format($array,$type=''){
        $data = json_decode($array,true);
        foreach ($data as $key => $value){
            $data[$key]['classify'] = $type;
        }
        return $data;
    }

    /**
     * Desc:领取状态列表
     * User: mf
     * Time: 2023/10/25 15:56
     * @param $code
     * @return string
     */
    public static function statusList($code,$type='')
    {
        $array = array(
            '-1'=>'我要解锁',
            '0'=>'未领取 ',
            '1'=>'待核销',

        );
        if($type==1){
            $array['2']='已核销';
        }
        if($type==2){
            $array['2']='已发放';
        }

        return $array[$code];
    }

    public static function identity()
    {
        $identity = array(
            '0'=>'不限制',
            '1'=>'团长',
            '2'=>'团长+团员',
            '3'=>'团员',
            '4'=>'仅限支付客户',
        );
        return $identity;
    }

    public static function conditionStatistics($system,$themeid,$myworker)
    {

        $tiaojian = "themeid=" .$themeid;
        if ($myworker['level'] == '1'){
            $tiaojian .= "";
        }elseif ($myworker['level'] == '2'){
            $tiaojian .= "  and shangjiaid=" . $myworker['company'];
        }else{
            $tiaojian .= Worker::getWokerid($system,$myworker['uid'],' and workerid ');
        }

        $gift_config = db_get(t_intive_gift_config,array('software'=>MODULE_NAME,'themeid'=>$themeid));
        $tuan_gift = self::format($gift_config['tuan_gift'],'tuan_gift');
        $invite_gift = self::format($gift_config['invite_gift'],'invite_gift');
        $gift_array = array_merge($tuan_gift,$invite_gift);
        $list = [];
        $numberall = 0;
        foreach ($gift_array as $key => $value){
            $sql = "select count(id)  from ".tablename(t_intive_gift_record)." where ".$tiaojian." and taskid={$value['taskid']} and classify ='{$value['classify']}'";
            $gift_record_count = intval(db_fetchcolumn($sql));

            $identity_text = self::identity()[$value['identity']];
            if($value['classify']=='tuan_gift'){
                $name = '成团'.$value['number'].'人【'.$identity_text.'】';
            }else{
                $name = '邀请'.$value['number'].'人【'.$identity_text.'】';
            }
            $list[$key]['name'] = $name;
            $list[$key]['taskid'] = $value['taskid'];
            $list[$key]['classify'] = $value['classify'];
            $list[$key]['number'] = $gift_record_count;
            $numberall += $list[$key]['number'];
        }
        $array = [
            [
                'name'=>'全部',
                'taskid'=>-1,
                'classify'=>'',
                'number'=>$numberall
            ]
        ];
        $list = array_merge($array,$list);
        return $list;
    }

    public static function giftRecord($baseinfo,$themeid)
    {
        global $_P;
        $taskid = intval($_P['taskid']);
        $classify = $_P['classify'];
        $page = intval($_P['page'])?intval($_P['page']):0;
        $myworker = $baseinfo['myworker'];
        $system = $baseinfo['system'];
        if ($myworker['level'] == '1'){
            $tiaojian = "";
        }elseif ($myworker['level'] == '2'){
            $tiaojian = "  and r.shangjiaid=" . $myworker['company'];
        }else{
            $tiaojian = Worker::getWokerid($system,$myworker['uid'],' and r.workerid ');
        }

        $where = "r.themeid='$themeid' " .$tiaojian;
        if($taskid!=-1){
            $where .= "  and r.classify='$classify'  and r.taskid='$taskid'";
        }
        $limit = " LIMIT ".($page*20).",20 ";
        $sql = "
                select 
                    r.id,r.status,r.exchange_at,g.name as gift_name,f.username,f.mobile,f.avatar,w.username as workername
                from 
                ".tablename(t_intive_gift_record)."  as r 
                left join ".tablename(t_intive_gift)." as g   on g.id=r.gift_id  
                left join ".tablename(t_fans)." as f   on f.uid=r.uid 
                left join ".tablename(t_worker)." as w on w.uid=r.workerid  
                 where ".$where."  order by  r.id desc
                ";
        $list = db_select($sql.$limit);
        foreach ($list as $key => $value){
            $list[$key]['order'] = $value['id']+985;
        }
        return $list;
    }
    
    public  static function getGiftList($themeid,$search_data)
    {
        $where = '';
        if($search_data){
             $where .= " and name like  '%".$search_data."%'";
        }
        $sql = "select * from ".tablename(t_intive_gift)."  where software='".MODULE_NAME."' and themeid=$themeid and status=1 {$where} order by id asc";
        return db_select($sql);
    }

    public  static function getGiftItemById($themeid,$id)
    {
        $sql = " select a.id,a.shangjiaid,a.name,a.top_img,a.price,a.status,a.type,a.remark,b.name as shangjia_name from " . tablename(t_intive_gift) . " as a " .
            "left join " . tablename(t_shangjia) . " as b on a.shangjiaid=b.id " .
            " where a.software='".MODULE_NAME."' and a.themeid=$themeid and a.id=$id";
        return db_find($sql);
    }

    public  static function insertGift($data)
    {
        return $insertid = db_insert(t_intive_gift,$data);
    }

    public  static function editGiftItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_intive_gift,$data,$where);
    }
    //查询所有礼品
    public  static  function getGiftAllList($themeid,$type=1,$status=1){
         $field = array();
         if($type==2){
             $field = ['id','name'];
         }
         $where['software'] = MODULE_NAME;
         $where['themeid'] = $themeid;
         if($status){
             $where['status'] = 1;
         }
         $list = db_getall(t_intive_gift,$where,$field,'id');
         return $list;
    }

    public  static function getShangjiaList()
    {
        $sql = " select id,name,state from ".tablename(t_shangjia)." where id >0 and state=1 order by displayorder";
        return db_select($sql,array(),'id');
    }

    public static function getTeamList(){
        return db_select("SELECT id,company,name FROM ".tablename (t_team),array(),'id');
    }

    public static function getWorkerList($themeid)
    {
        $worker_list =  db_select("SELECT id,themeid,uid,username,company,team,superior,level FROM ".tablename ( t_worker)." WHERE  themeid = {$themeid} and level<=3");
        $team_list = self::getTeamList();
        $company_list = self::getShangjiaList();
        foreach ($worker_list as $key => $w){
                if($w['team']){
                    $worker_list[$key]['teamname'] = $team_list['name'];
                }else{
                    $worker_list[$key]['teamname'] = '';
                }
                if($w['companyname']){
                    $worker_list[$key]['companyname'] = $company_list['name'];
                }else{
                    $worker_list[$key]['$company_list'] = '';
                }
        }
        return $worker_list;
    }
    //查询领取列表
    public  static function getGainRecord($themeid,$where_arr,$page_start=0,$page_size=10,$count = false){
            $condition = "";
            $shangjiaid = isset($where_arr['shangjiaid'])?$where_arr['shangjiaid']:0;
            $uid = isset($where_arr['uid'])?$where_arr['uid']:0;
            $type = isset($where_arr['type'])?$where_arr['type']:0;
            $status = isset($where_arr['status'])?$where_arr['status']:0;
            $name = isset($where_arr['name'])?$where_arr['name']:'';
            $starttime = isset($where_arr['starttime'])?$where_arr['starttime']:'';
            $endtime = isset($where_arr['endtime'])?$where_arr['endtime']:'';
            $time_type = isset($where_arr['time_type'])?$where_arr['time_type']:1;
            $gift_id = isset($where_arr['gift_id'])?$where_arr['gift_id']:0;
            $classify = isset($where_arr['classify'])?$where_arr['classify']:'';

            if ($shangjiaid){
                $condition .= " and r.shangjiaid = $shangjiaid";
            }

            if ($uid){
                $condition .= " and r.uid = $uid";
            }

            if ($type>0){
                $condition .= " and r.type = $type";
            }

            if ($status>0){
                $condition .= " and r.status = $status";
            }else{
                $condition .= " and r.status > $status";
            }

            $time_field = 'r.created_at';
            if($time_type==2){
                $time_field = 'r.exchange_at';
            }

            if($starttime){
                $condition .= " and $time_field >= '{$starttime}'";
            }

            if($endtime){
                $condition .= " and $time_field <= '{$endtime}'";
            }

            if ($classify){
                $condition .= " and r.classify = '$classify'";
            }

            if ($gift_id>0){
                $condition .= " and r.gift_id = $gift_id";
            }

            if ($name){
                $condition .= " and r.name like '%".$name."%' or r.name like '%".$name."%' ";
            }
            if ($page_size && !$count){
                $condition .= " limit ".$page_start.",".$page_size;
            }

            $sql = "  from ".tablename(t_intive_gift_record)." as r".
                " LEFT JOIN ".tablename(t_fans)." AS f on r.uid=f.uid ".
                " where r.themeid=$themeid".$condition;
            if ($count){
                $count_sql = " SELECT  count(r.id)  ".$sql;
                return  intval(db_fetchcolumn($count_sql));
            }else{
                $data_sql = " select r.*,f.avatar,f.nickname,f.username,f.mobile,f.workerid ".$sql;
                return db_select($data_sql);
            }
    }

    public static  function getGiftStatusList($themeid){
                $sql = " SELECT  count(id) as count,
                                  count(case when status=-1 then 1 end) as lock_num,
                                  count(case when status=0 then 1 end) as not_gain_num,
                                  count(case when status=1 then 1 end) as gain_num,
                                  count(case when status=2 then 1 end) as exchange_num
                 from ".tablename(t_intive_gift_record)." where themeid = {$themeid} ";
                return  db_find($sql);
    }

    //查询
    public  static function getGainUserList($system,$config,$themeid,$search,$page_start=0,$page_size=0,$count = false,$isexport = false)
    {

        if($system['is_multiple_merchants'] && $config['showshop']==0){
            $company_list = db_select("SELECT id,name FROM ".tablename (t_shangjia),array(),'id');
        }else{
            $company_list = array();
        }
        //查询团队
        $team_list =  db_select("SELECT id,company,name FROM ".tablename (t_team),array(),'id');
        $worker_list =  db_select("SELECT id,themeid,uid,username,company,team,superior,level,concat(themeid,'_',uid) as theme_uid FROM ".tablename ( t_worker)." WHERE  themeid = {$themeid}" ,array(),'theme_uid');

        $type = $search['type'];
        $condition = "";
        $having = "";
        switch($type){
            case 1:      //已支付
                $condition .= " and r.status = 1";
                break;
            case 2:     //未支付
                $condition .= " and (r.status = 0 or r.status IS NULL)";
                break;
        }

        if($search['classify']){
            $condition .= " and g.classify = '{$search['classify']}'";
        }

        if($search['status']){
            $condition .= " and g.status = {$search['status']}";
        }

        if($search['gift_id']){
            $condition .= " and g.gift_id = '{$search['gift_id']}'";
        }

        $workerid = isset($search['workerid'])?intval($search['workerid']):0;
        if($workerid){
            $condition .= " and f.workerid = {$workerid}";
        }

        $search_keyword = $search['$search_data'];
        if ($search_keyword){
            $condition .= " and f.uid ='{$search}' or f.nickname like '".$search."'"." or f.mobile like '".$search."' " ." or f.username like '".$search."' ";
        }

        $sql = " from ".tablename(t_intive_gift_record)." as g 
                 left join " .tablename(t_fans)." as f on f.uid=g.uid and f.themeid=$themeid
                 LEFT JOIN ".tablename(t_record)." AS r ON g.uid=r.uid and r.themeid=$themeid
                 WHERE g.themeid=$themeid ";

        if ($count){
            $count_sql ="select count(distinct g.uid) as count,
                          count(case when g.status=-1 then 1 end) as lock_num,
                          count(case when g.status=0 then 1 end) as not_gain_num,
                          count(case when g.status=1 then 1 end) as gain_num,
                          count(case when g.status=2 then 1 end) as exchange_num
                          ".$sql.$condition .$having;

            $all_data = db_find($count_sql);
            return $all_data;
        }else{
            $limit = '';
            if ($page_size) {
                $limit = " LIMIT ".$page_start.",".$page_size;
            }

            $gift_array = self::getGiftAllList($themeid,2,0);

            $list_sql = " select f.id as fanid,f.uid,f.nickname,f.avatar,f.username,f.mobile,f.workerid,r.id as recordid,r.type,r.addtime,r.status,
                          group_concat(concat_ws('-',g.gift_id,g.status,g.classify))as gifts 
                    ".$sql.$condition .'  group by g.uid '.$having.' ORDER BY g.uid asc '.$limit;

            $all_list = db_select($list_sql,array(),'uid');
            if ($config['yukuan'] > 0 && TIMESTAMP > $config['yukuantime']) {
                $userlist = Fans::getWeiBukuanList($config,$themeid);
            }
            foreach ($all_list as $key=>$val){
                $invite_gift = '';
                $tuan_gift = '';
                $invite_exchange_gift='';
                $tuan_exchange_gift='';
                if($val['gifts']){
                    $gift_arr = explode(',',$val['gifts']);
                    foreach ($gift_arr as $g){
                        $gift_info = explode('-',$g);
                        $gift_id = $gift_info[0];
                        $gift_status = $gift_info[1];
                        $gift_type = $gift_info[2];
                        $gift = $gift_array[$gift_id];
                        if($gift){
                            $gift_name = $gift['name'];
                            if($gift_type=='invite_gift'){       //邀请礼
                                $invite_gift .= $invite_gift?'|'.$gift_name:$gift_name;
                                if($gift_status==2){
                                    $invite_exchange_gift .= $invite_gift?'|'.$gift_name:$gift_name;
                                }
                              }elseif ($gift_type=='tuan_gift'){  //成团礼
                                $tuan_gift .= $tuan_gift?'|'.$gift_name:$gift_name;
                                if($gift_status==2){
                                    $tuan_exchange_gift .= $tuan_exchange_gift?'|'.$gift_name:$gift_name;
                                }
                            }
                        }
                    }
                }

                $all_list[$key]['invite_gift'] = $invite_gift;
                $all_list[$key]['tuan_gift'] = $tuan_gift;
                $all_list[$key]['invite_exchange_gift'] = $invite_exchange_gift;
                $all_list[$key]['tuan_exchange_gift'] = $tuan_exchange_gift;

                $worker = '';
                if($val['workerid']){
                    $worker_info = $worker_list[$themeid.'_'.$val['workerid']];
                    if($worker_info){
                        $worker .= $worker_info['username'].' ';
                    }

                    if($team_list[$worker_info['team']]){
                        $team_info = $team_list[$worker_info['team']];
                        $worker .= $team_info['name'].' ';
                    }

                    if($company_list[$worker_info['company']]){
                        $company_info = $company_list[$worker_info['company']];
                        $worker .= $company_info['name'];
                    }
                }

                $all_list[$key]['worker']  = $worker;
                $all_list[$key]['pay_status'] = getPayStatus($config,$themeid,$userlist,$val['recordid'],$val['status'],$val['addtime'],$val['type'],$isexport);
            }
            return  $all_list;
        }
    }

    /**
     * Desc:获取礼品统计数据
     * User:wyx
     * Time: 2023/11/1 11:05
     * @param $themeid
     * @param $type   1返回全部 2返回成团礼 3返回邀请礼
     * @param $where_arr
     * @return array[]
     */
    public  static function getGiftCount($themeid,$where_arr){
            $gift_list= self::getGiftAllList($themeid,2,0);
            $where = '';

            $sql = "select  gift_id,classify,count(case when status=1 then 1 end) as total,count(case when status=2 then 1 end) as exchange_total
                   from ".tablename(t_intive_gift_record)." 
                   WHERE themeid=$themeid {$where} group by  gift_id,classify";

            $gift_all_data = db_select($sql);
            $tuan_gift_data = [];
            $tuan_gift_total = 0;
            $tuan_gift_exchange_total = 0;

            $invite_gift_data = [];
            $invite_gift_total = 0;
            $invite_gift_exchange_total = 0;

            $help_gift_data = [];
            $help_gift_total = 0;
            $help_gift_exchange_total = 0;

            foreach ($gift_all_data as $g){
                $gift_info = $gift_list[$g['gift_id']];
                if($gift_info){
                    $name = $gift_info['name'];
                }else{
                   $name = '未知';
                }

                $gift_data['id'] = $g['gift_id'];
                $gift_data['name'] =$name;
                $gift_data['total'] = $g['total'];
                if (isset($g['exchange_total'])) {
                   $gift_data['exchange_total']=$g['exchange_total'];
                }

                if($g['classify']=='tuan_gift'){
                    $tuan_gift_total+=$g['total'];
                    if (isset($g['exchange_total'])){
                       $tuan_gift_exchange_total+=$g['exchange_total'];
                    }
                    $tuan_gift_data[] = $gift_data;
                }elseif($g['classify']=='invite_gift'){
                    $invite_gift_total+=$g['total'];
                    if (isset($g['exchange_total'])){
                        $invite_gift_exchange_total+=$g['exchange_total'];
                    }
                    $invite_gift_data[] = $gift_data;
                }elseif($g['classify']=='help_gift'){
                    $help_gift_total+=$g['total'];
                    if (isset($g['exchange_total'])){
                        $help_gift_exchange_total+=$g['exchange_total'];
                    }
                    $help_gift_data[] = $gift_data;
                }
                unset($gift_data);
            }

            $tuan_all['id']  = 0;
            $tuan_all['name']  = '全部';
            $tuan_all['total']  = $tuan_gift_total;
            $tuan_all['exchange_total']  = $tuan_gift_exchange_total;
            array_unshift( $tuan_gift_data,$tuan_all);

            $invite_all['id']  = 0;
            $invite_all['name']  = '全部';
            $invite_all['total']  = $invite_gift_total;
            $invite_all['exchange_total']  = $invite_gift_exchange_total;
            array_unshift( $invite_gift_data,$invite_all);

            $help_all['id']  = 0;
            $help_all['name']  = '全部';
            $help_all['total']  = $help_gift_total;
            $help_all['exchange_total']  = $help_gift_exchange_total;
            array_unshift( $help_gift_data,$help_all);

            return  [
                  'tuan_gift' => $tuan_gift_data,
                  'invite_gift' => $invite_gift_data,
                  'help_gift' => $help_gift_data,
                ];
    }

    /**
     * Desc:删除关系记录检测
     * User:wyx
     * Time: 2023/11/2 14:40
     * @param $themeid
     * @param $classify
     * @param $task_id
     * @return int
     */
    public static function deleteCheckGift($themeid,$classify,$taskid){
        $where = '';
        if($taskid>0){
            $where.=" AND taskid = {$taskid}";
        }
        $count = "select  count(*)  from  ".tablename(t_intive_gift_record)."  WHERE themeid = {$themeid} AND  classify = '{$classify}' {$where}";
        $res = db_fetchcolumn($count);
        if($res==0){
            return true;
        }else{
            return false;
        }
    }
    /**
     * Desc:删除礼品绑定关系检测
     * User:wyx
     * Time: 2023/11/9 10:54
     * @param $themeid
     * @param $gift_id
     * @return bool
     */
    public static function checkConfigGift($themeid,$gift_id){
        $config = self::getGiftConfig($themeid);
        $tuan_gift = $config['tuan_gift'];
        $invite_gift = $config['invite_gift'];

        $msg = [];
        foreach ($tuan_gift as $t){
            if($t['gift_id'] == $gift_id ){
                $msg[] = '成团礼：'.$t['number'].'人成团已绑定此奖品';
            }
        }
        foreach ($invite_gift as $i){
            if($i['gift_id'] == $gift_id ){
               $msg[] = '邀请下单礼：邀请'.$t['number'].'人下单已绑定此奖品';
            }
        }
        if($msg){
            return ['status'=>0,'msg'=>$msg[0]];
        }else{
            return ['status'=>1,'msg'=>''];
        }
    }

    /**
     * Desc:获取产品
     * User:wyx
     * Time: 2023/11/17 14:16
     * @param $themeid
     * @return mixed
     */
    public static function getGiftConfig($themeid){
        $gift_config = db_get(t_intive_gift_config, array('software'=>MODULE_NAME,'themeid'=>$themeid));
        if($gift_config['tuan_gift']){
            $gift_config['tuan_gift'] = json_decode($gift_config['tuan_gift'],true);
        }else{
            $gift_config['tuan_gift'] = [];
        }

        if($gift_config['invite_gift']){
            $gift_config['invite_gift'] = json_decode($gift_config['invite_gift'],true);
        }else{
            $gift_config['invite_gift'] = [];
        }

        if($gift_config['help_gift']){
            $gift_config['help_gift'] = json_decode($gift_config['help_gift'],true);
        }else{
            $gift_config['help_gift'] = [];
        }
        return $gift_config;
    }

    /**
     * Desc获取礼品名称长度,超过8个汉字配置改成长标题展示模式
     * User:wyx
     * Time: 2023/11/4 14:28
     * @param $themeid
     */
    public  static function  getGiftNameLength($themeid){
        $checkNameSql =  "select count(id) from ".tablename(t_intive_gift)." where CHAR_LENGTH(name)>=8 and software ='".MODULE_NAME."' and themeid = {$themeid}";
        $checkName =   db_fetchcolumn($checkNameSql);
        if($checkName>1){ //超过8个汉字
            db_update(t_intive_gift_config,['style_mode'=>2], array('software'=>MODULE_NAME,'themeid'=>$themeid));
        }else{
            db_update(t_intive_gift_config,['style_mode'=>1], array('software'=>MODULE_NAME,'themeid'=>$themeid));
        }
    }


    /**
     * Desc:获取用户能添加的配置礼品
     * User:wyx
     * Time: 2023/11/17 14:18
     * @param $themeid
     * @param $uid
     * @return array[]
     */
    public static  function  getUserCanInviteGift($themeid,$uid){
        $userRecordSql = "select * from  ".tablename(t_intive_gift_record)."  WHERE themeid = {$themeid} AND  uid = {$uid}";
        $userRecord = db_select($userRecordSql);
        $giftConfig = self::getGiftConfig($themeid);

        $exitTuanTaskid = [];
        $exitInviteTaskid = [];
        foreach ($userRecord as $k=>$r){
            if($r['classify']=='tuan_gift'){
                $exitTuanTaskid[] = $r['taskid'];
            }else{
                $exitInviteTaskid[] = $r['taskid'];
            }
        }

       $giftList = self::getGiftAllList($themeid);
       $giftArr = [];
        if($giftConfig['tuan_gift']){
            foreach ($giftConfig['tuan_gift'] as $g){
                   if(!in_array($g['taskid'],$exitTuanTaskid)){
                       $giftInfo = $giftList[$g['gift_id']];
                       if($giftInfo&&$giftInfo['status']==1){
                           $giftType = $giftInfo['status']==1?'实物':'红包';
                           $giftArr[] =[
                                   'type' => 'tuan_gift',
                                   'gift_id' => $g['gift_id'],
                                   'taskid' => $g['taskid'],
                                   'name' =>'成团礼-'.$g['number']."人成团-".$giftInfo['name']."[".$giftType.":".$giftInfo['price']."元]",
                           ];
                       }
                   }
            }
        }
        if($giftConfig['invite_gift']){
            foreach ($giftConfig['invite_gift'] as $g){
                if(!in_array($g['taskid'],$exitInviteTaskid)){
                    $giftInfo = $giftList[$g['gift_id']];
                    if($giftInfo&&$giftInfo['status']==1){
                        $giftType = $giftInfo['status']==1?'实物':'红包';
                        $giftArr[] =[
                            'type' => 'tuan_gift',
                            'gift_id' => $g['gift_id'],
                            'taskid' => $g['taskid'],
                            'name' =>'邀请礼-'.'邀请'.$g['number']."人-".$giftInfo['name']."[".$giftType.":".$giftInfo['price']."元]"
                        ];
                    }
                }
            }
        }
        return ['gift_arr' => $giftArr];
    }

    public static  function  addUserGiftRecord($themeid,$uid,$classify,$taskid,$gift_id){
        //$giftConfig =  self::getGiftConfig($themeid);
        $allGift =  self::getGiftAllList($themeid);
        $giftInfo = $allGift[$gift_id];
        $data['themeid'] = $themeid;
        $data['uid'] = $uid;
        $data['classify'] = $classify;
        $data['gift_id'] = $gift_id;
        $data['taskid'] = $taskid;
        $data['type'] = $giftInfo['type'];
        $data['created_at'] = date('Y-m-d H:i:s',time());
        $res = $insertid = db_insert(t_intive_gift_record,$data);
        if($res){
            return true;
        }else{
            return false;
        }
    }

}